package com.threadlocal.demo;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

/**
 * @ClassName: ConnectionManager
 * @Description: https://www.pdai.tech/md/java/thread/java-thread-x-threadlocal.html
 * @Author: PAUL XUE
 * @Date: 2022/1/13 11:19 AM
 * @Version: 1.0
 **/
public class ConnectionManagerV2 {
    private Connection conn = null;
    private String url = "jdbc:mysql://172.16.196.49:3306/posx_prd?useSSL=false&useUnicode=true&characterEncoding=utf8&characterSetResults=utf8&useSSL=false&serverTimezone=Hongkong&zeroDateTimeBehavior=convertToNull";

    public Connection openConnection() {
        try {
            if (conn == null) {
                conn = DriverManager.getConnection(url);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return conn;
    }

    public void closeConnection() {
        try {
            if (conn != null)
                conn.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    class Dao {
        public void insert() {
            ConnectionManagerV2 connectionManager = new ConnectionManagerV2();
            Connection connection = connectionManager.openConnection();
            //    使用connection操作
            connectionManager.closeConnection();
        }
    }
}
